<?php

require( 'util.php' );

validate_action_post( array( 'userName', 'password' ) );

//-----------------------------------------

require( 'dbconnect.php' );

$user_name = mysql_real_escape_string( $_POST['userName'] );
// 先检测管理员登录
admin_login( $user_name, $_POST['password'] );

$sql = "SELECT u_id, name, mail, birthday, password, gender, occupation, blood_type, weibo, qq, s_question, s_answer, address, u_image, phone, `group` FROM `user` WHERE name = '$user_name'";
$result = mysql_query( $sql ) or report_err_and_exit( mysql_error() );
$userInfo = mysql_fetch_array( $result );

if( $userInfo )
{
	if( $userInfo['password'] == $_POST['password'] )
	{
		session_start();
		$_SESSION['u_id'] = $userInfo['u_id'];
		$_SESSION['userName'] = $userInfo['name'];
		$_SESSION['gender'] = $userInfo['gender'];
		$_SESSION['group'] = $userInfo['group'];
		$_SESSION['phone'] = $userInfo['phone'];
		$_SESSION['address'] = $userInfo['address'];
		$_SESSION['birthday'] = $userInfo['birthday'];
		$_SESSION['occupation'] = $userInfo['occupation'];
		$_SESSION['blood_type'] = $userInfo['blood_type'];
		$_SESSION['weibo'] = $userInfo['weibo'];
		$_SESSION['qq'] = $userInfo['qq'];
		$_SESSION['u_image'] = $userInfo['u_image'];
		$_SESSION['s_question'] = $userInfo['s_question'];
		$_SESSION['s_answer'] = $userInfo['s_answer'];
		$_SESSION['mail'] = $userInfo['mail'];
		$_SESSION['password']=$userInfo['password'];
		
		redirect_and_exit( 'index.php', '登录成功' );
	}
	else
	{
		report_err_and_exit( '密码错误' );
	}
}
else
{
	report_err_and_exit( '用户名不存在' );
}

function admin_login($admin, $password)
{
	$sql = "SELECT a_password FROM `admin` WHERE a_name = '$admin'";
	$result = mysql_query( $sql ) or report_err_and_exit( mysql_error() );
	$row = mysql_fetch_array( $result );
	
	if ($row['a_password'] == $password)
	{
		// 管理员登录成功
		session_start();
		$_SESSION['admin'] = $admin;
		
		redirect_and_exit( 'administrator.php', '管理员登录成功' );
	}
}

?>